// CountPOAClient.java  Static Client, VisiBroker for Java
package Server3;

import org.omg.CosNaming.*;
import java.util.Random;

class CountPOAClient
{
        public static void main(String args[]) {
        final int totalIncrements = 100;

        try
    { // Initialize the ORB
      System.out.println("Initializing the ORB");
      org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(args, null);


      // Get a reference to the Naming service
      org.omg.CORBA.Object nameServiceObj =
          orb.resolve_initial_references ("NameService");
      if (nameServiceObj == null)
          {
              System.out.println("nameServiceObj = null");
              return;
          }

      org.omg.CosNaming.NamingContext nameService =
          org.omg.CosNaming.NamingContextHelper.narrow (nameServiceObj);
      if (nameService == null)
          {
              System.out.println("nameService = null");
              return;
          }

     
      CounterPOA.Count[] counterArray = new CounterPOA.Count[1000];
      Random randomGen = new Random();
     
      for (int x = 0; x < 1000; x++) {
              // resolve the Count object in the Naming service
              NameComponent[] countName = {new NameComponent("countName".concat(String.valueOf(x+1)), "")};
              counterArray[x] = CounterPOA.CountHelper.narrow(nameService.resolve(countName));
             
           // Set sum to initial value of 0
//                    counterArray[x].sum((int)0);
      }
     
      
      int[] trackArray = new int[10];
      for (int x=0; x<10; x++)
    	  trackArray[x] = 0;
      
      // Calculate Start time
      long startTime = System.currentTimeMillis();

      for (int i = 0; i < totalIncrements; i++) {
          if (i % (totalIncrements/10) == 0)
                  System.out.println(i + "/" + totalIncrements + " done");
          int rand = randomGen.nextInt(10);
          counterArray[rand].increment();
          trackArray[rand]++;
//          counterArray[200].increment();
      }
      System.out.println(counterArray[200].sum());   
      // Calculate stop time; print out statistics
      long stopTime = System.currentTimeMillis();
     
      System.out.println("Avg time to increment a counter = " + ((stopTime - startTime)/1000000f) + " msecs");
     
      int average = 0;
//      for (int x = 0; x < 1000; x++)
//          average += counterArray[x].sum();
//
//          System.out.println("Average Sum: " + (double) average/1000f);      
      
    for (int x = 0; x < 10; x++) {
    	System.out.println("Sum for " + (x+1) + " = " + trackArray[x]);     
    	average += trackArray[x];
    }
    System.out.println("Total = " + average);     
 
    } catch(Exception e)
    { System.err.println("Exception");
      System.err.println(e);
    }
  }
}

